package com.ruizhong.centercontroll.aspect;

import com.ruizhong.centercontroll.aspect.myAnnotation.checkLogin;
import com.ruizhong.centercontroll.entity.TUser;
import com.ruizhong.centercontroll.entity.TUserPermission;
import com.ruizhong.centercontroll.service.TUserService;
import com.ruizhong.centercontroll.service.impl.TUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class UserAspect {

    @Autowired
    private TUserService tUserService;

    @Pointcut("@annotation(com.ruizhong.centercontroll.aspect.myAnnotation.checkLogin)")
    public void checkLoginPointCut() {
    }


    @Before("checkLoginPointCut()")
    public void checkLogin(JoinPoint joinPoint) throws NoSuchFieldException, IllegalAccessException {
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();

        // 2. 从Header获取Token（实际项目可能用Authorization头）
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            throw new RuntimeException("Token不能为空");
        }
        if (!TUserServiceImpl.tokenMapUser.containsKey(token)) {
            throw new RuntimeException("请先登录");
        }
        String annotationValue = getCheckLoginAnnotationValue(joinPoint);

        if (StringUtils.isEmpty(annotationValue)) {
            log.info("获取到@checkLogin的value值为空");
            return;
        }
        TUser user = TUserServiceImpl.tokenMapUser.get(token);
        TUserPermission permissionsByUserId = tUserService.getPermissionsByUserId(user.getId());
        Field declaredField = permissionsByUserId.getClass().getDeclaredField(annotationValue);
        declaredField.setAccessible(true);
        Integer value = (Integer) declaredField.get(permissionsByUserId);
        log.info("获取到@checkLogin的value值: {}", annotationValue);
        log.info("当前用户的权限值 {}", value);
        if (value == 0) {
            return;
        }
        if (value == 2) {
            throw new RuntimeException("无权执行此操作");
        }
        if (value == 1){
            String checkedPassword = request.getHeader("checkedPassword");
            if (StringUtils.isEmpty(checkedPassword) || checkedPassword.equals("false")){
                throw new RuntimeException("需要输入密码以执行本次操作");
            }else if (checkedPassword.equals("true")){
                return;
            }
        }
    }

    private String getCheckLoginAnnotationValue(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        checkLogin annotation = method.getAnnotation(checkLogin.class);
        return annotation.value(); // 获取注解的value属性值
    }
}
